package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Employee;
import com.itheima.common.PageParam;
import com.itheima.dao.EmployeeDao;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;

    /**
     * 登录
     *  : 其实就是按照账号和密码来查询员工信息
     * @param employee
     * @return
     */
    @Override
    public Employee login(Employee employee) {

        //1. 创建条件对象
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();

        //2. 追加条件
        lqw.eq(Employee::getUsername , employee.getUsername());

        //要对密码进行加密，这样去匹配数据库的时候，就能匹配上了。
        String pwd = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        lqw.eq(Employee::getPassword , pwd);

        //追加状态值的判定
        lqw.eq(Employee::getStatus , 1);

        //3. 执行查询
        return employeeDao.selectOne(lqw);
    }

    /**
     * 添加员工
     *
     * @param employee
     * @return 影响行数
     */
    @Override
    public int add(Employee employee) {
        return employeeDao.insert(employee);
    }

    /**
     * 员工分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Employee> page(PageParam pageParam) {

        //1. 构建分页对象
        IPage<Employee> page = new Page<>(pageParam.getPage() , pageParam.getPageSize());

        //2. 创建条件对象
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();

        //3. 追加条件
        //如果name属性不为空，就追加条件。
        lqw.like(pageParam.getName() != null , Employee::getName , pageParam.getName());

        //4. 执行查询  select * from employee where name like '%zhangsan%' limit 0 , 10 ;
        return employeeDao.selectPage(page , lqw );
    }

    /**
     * 更新员工
     *
     * @param employee
     * @return
     */
    @Override
    public int update(Employee employee) {
        return employeeDao.updateById(employee);
    }
}
